# coding:utf-8

import os
import json

from collections import defaultdict

import set_env_path     # 请勿删除


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


Base = declarative_base()
engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def sync_pack_areas():
    """
    create by ld_wu 2017-09-01
    原抢套餐表中的area_id只支持输入省份
    目前需要area_id的内容更新为省份所在城市
    :return:
    """
    select_city_sql = """
    select id, pid from area where type=2
    """

    update_pack_sql = """
    update pack set area_id=:area_ids where id=:id
    """

    cities = session.execute(select_city_sql).fetchall()
    city_ids = [each.id for each in cities]
    pro_city_map = defaultdict(list)

    for city in cities:
        pro_city_map[city.pid].append(city.id)

    for pack in session.execute('select * from pack').fetchall():
        area_ids = list()
        pro_ids = json.loads(pack.area_id) if pack.area_id else list()
        for pid in pro_ids:
            c_ids = [pid] if pid in city_ids else pro_city_map[pid]
            area_ids.extend(c_ids)
        session.execute(
            update_pack_sql,
            {
                'area_ids': json.dumps(sorted(list(set(area_ids)))),
                'id': pack.id
            }
        )
        session.commit()


if __name__ == '__main__':
    sync_pack_areas()
